<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        <form action="upload.php">
            <input type="file" id='file'>
        </form>
        <p id='msg'></p>
    </div>
</body>

<script src='../../js/jquery.js'></script>
<script>

    var bytesPerPiece = 1024 * 1024; // 每个文件切片大小定为1MB .
    var totalPieces;

    //监听上传
    $('#file').change(function(){
        
        $('#msg').text('上传中...');
        var file = this.files[0];

        var start = 0;
        var end;
        var fileSize = file.size;
        var fileName = file.name;
        var index = 0;

        console.log(file,fileName);
        totalPieces = Math.ceil(fileSize/bytesPerPiece);   //上传次数


        //循环上传
        while(start<fileSize){
            end = start+bytesPerPiece;  //结束位置

            if(end>bytesPerPiece){
                end = fileSize;
            }
            
            var chunk = file.slice(start,end);  //开始分片
            chunk.index  = index;

            var formData = new FormData();
            formData.append('file',chunk,fileName);

            $.ajax({
                    url: 'upload.php',
                    type: 'POST',
                    cache: false,
                    data: formData,
                    processData: false,   //不序列化
                    contentType: false,   
                    async:false,          //同步上传
                    dataType: "json",   
                }).done(function(res){ 
                    console.log(res);
                   if(res.code==200){
                    index++;
                   }else{
                    $('#msg').text('上传失败');
                    break;
                   }
                   
                }).fail(function(res) {
                    $('#msg').text('网络繁忙');
                })
   
            start = end;   //开始位置
        }


        if(index>=totalPieces){
            $('#msg').text('上传成功');
        }

    })
</script>
</html>